package MainClasses.FromAPCompSci;

import java.util.*;

public class MyMap<K, V>
{
    private ArrayList<MapEntry<K, V>> entries;

    public MyMap()
    {
        entries = new ArrayList<MapEntry<K, V>>();
    }

    //helper method that returns the index of the entry with given key;
    //returns -1 if no such entry exists
    private int findIndex(Object key)
    {
        for(int i = 0; i < entries.size(); i++)
        {
            if(key.equals(entries.get(i).getKey()))
            {
                return i;
            }
        }
        return -1;
    }
    
    public int size()
    {
        return entries.size();
    }
    
    //added Monday November 12, 2007
    public ArrayList<MapEntry<K,V>> getEntries()
    {
        return entries;
    }

    public boolean containsKey(Object key)
    {
        int index = findIndex(key);
        if(index < 0)
            return false;
        return true;
    }

    // associates key with value
    // returns the value formerly associated with key
    // or null if key was not present
    public V put(K key, V value)
    {
        int index = findIndex(key);
        if(index < 0)
        {
            entries.add(new MapEntry(key, value));
            return null;
        }
        V oldvalue = entries.get(index).getValue();
        entries.set(index, new MapEntry(entries.get(index).getKey(), value));
        return oldvalue;
    }

    // returns the value associated with key
    // or null if there is no associated value
    public V get(Object key)
    {
        int index = findIndex(key);
        if(index < 0)
            return null;
        return entries.get(index).getValue();
    }

    // removes and returns the value associated with key;
    // returns null if there is no associated value
    public V remove(Object key)
    {
        int index = findIndex(key);
        if(index < 0)
            return null;
        V oldvalue = entries.get(index).getValue();
        entries.remove(index);
        return oldvalue;
        
    }

    public MySet<K> keySet()
    {
        MySet<K> set = new MySet<K>();
        for(int i = 0; i < entries.size(); i++)
        {
            set.add(entries.get(i).getKey());
        }
        return set;
    }

    @Override
    public String toString()
    {
        String s = "";
        for (MapEntry<K, V> entry : entries)
            s += entry + " ";
        return s;
    }
}